/*
 * @lc app=leetcode.cn id=637 lang=cpp
 *
 * [637] 二叉树的层平均值
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    vector<double> averageOfLevels(TreeNode *root)
    {
        if (!root)
            return {};
        vector<TreeNode *> v[2];
        v[0].push_back(root);
        int inx = 0;
        vector<double> ans;
        while (v[inx].size())
        {
            double tmp = 0;
            for (auto n : v[inx])
            {
                tmp += n->val;
                if (n->left)
                    v[1 - inx].push_back(n->left);
                if (n->right)
                    v[1 - inx].push_back(n->right);
            }
            ans.push_back(tmp / v[inx].size());
            v[inx].clear();
            inx = 1 - inx;
        }
        return ans;
    }
};
// @lc code=end
